import { Message } from "element-ui";
import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter)
const routes = [
    {
        path: '/home',
        component: () => import('../pages/home/index')
    },
    {
        path: '/Detail',
        component: () => import('../pages/detail/index')
    },
    {
        path: '/center',
        component: () => import('../pages/center/index')
    },
    {
        path: '/applies',
        component: () => import('../pages/applies/index')
    },
    {
        path: '/orders',
        component: () => import('../pages/orders/index')
    },
    {
        path: '/address',
        component: () => import('../pages/address/index')
    },
    {
        path: '/cart',
        component: () => import('../pages/cart/index')
    },
    {
        path: '/confirm_order',
        component: () => import('../pages/confirm_order/index.vue')
    },
    {
        path: '/orders_Detail',
        component: () => import('../pages/orders_Detail/index.vue')
    },
    {
        path: '/',
        redirect: '/home'
    }
]

// 创建router实例
const router = new VueRouter({
    mode: 'history',
    routes // (缩写) 相当于 routes: routes
});

router.beforeEach((to, from, next) => {
    let publicPages = ['/home', '/detail'];
    let isLoggedIn = localStorage.getItem('token') != null;

    if (!isLoggedIn && !publicPages.includes(to.path)) {
        // 如果用户未登录且尝试访问非公开页面，重定向到登录页面
        Message({
            type: 'error',
            message: '无权限访问，请先登录'
        })
        next('/home');
    } else {
        // 如果用户已登录或正在访问公开页面，允许访问
        next();
    }
})

// 对外暴露
export default router